package com.travelsky.app.security.support;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.ui.webapp.AuthenticationProcessingFilter;

import com.travelsky.app.Exception.AuthCodeValidationException;

public class ValidateCodeAuthenticationProcessingFilter extends AuthenticationProcessingFilter {
	/**
	 * 验证验证码 
	 * @throws AuthenticationException 验证码验证失败
	 */
	public Authentication attemptAuthentication(HttpServletRequest request) throws AuthenticationException {
		String userName = request.getParameter("j_username");
		String kaptchaExpected = (String) request.getSession().getAttribute(
				com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		String kaptchaReceived = request.getParameter("kaptcha");

		if (kaptchaReceived == null || !kaptchaReceived.equalsIgnoreCase(kaptchaExpected)) {
			request.getSession().setAttribute(SPRING_SECURITY_LAST_USERNAME_KEY, userName);
			throw new AuthCodeValidationException("Invalid validation code");
		}
		return super.attemptAuthentication(request);
	}

}
